package com.coincalf.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.coincalf.dto.AgentRegisterDTO;
import com.coincalf.dto.RandCodeVerifyDTO;
import com.coincalf.entity.User;
import com.coincalf.entity.UserAuthAuditRecord;
import com.coincalf.entity.UserAuthInfo;
import com.coincalf.enums.AuthStatus;
import com.coincalf.feign.AccountServiceClient;
import com.coincalf.feign.RandCodeServiceClient;
import com.coincalf.feign.RewardServiceClient;
import com.coincalf.framework.enums.BaseStatus;
import com.coincalf.framework.enums.ResultCode;
import com.coincalf.framework.enums.SmsTemplate;
import com.coincalf.framework.enums.UserType;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.security.TokenProvider;
import com.coincalf.framework.security.UserDetails;
import com.coincalf.framework.utils.TokenUtil;
import com.coincalf.mapper.UserMapper;
import com.coincalf.service.UserAuthAuditRecordService;
import com.coincalf.service.UserAuthInfoService;
import com.coincalf.service.UserDetailsService;
import com.coincalf.service.UserService;
import com.coincalf.wallet.feign.UserInfoServiceClient;
import com.coincalf.wallet.feign.dto.UserInfoDTO;
import com.coincalf.web.vo.*;
import com.coincalf.web.vo.mappers.RegisterMapper;
import com.coincalf.web.vo.mappers.UserAuthInfoMapper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author qiang
 * @since 2018-05-12
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private UserAuthInfoService userAuthInfoService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TokenProvider tokenProvider;
    @Autowired
    private AccountServiceClient accountServiceClient;
    @Autowired
    private RewardServiceClient rewardServiceClient;
    @Autowired
    private RandCodeServiceClient randCodeServiceClient;
    @Autowired
    private UserInfoServiceClient userInfoServiceClient;
    @Autowired
    private UserAuthAuditRecordService userAuthAuditRecordService;

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return
     */
    @Override
    public User selectByUsername(String username) {
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("username", username);
        ew.or().eq("mobile", username);
        ew.or().eq("email", username);
        return super.selectOne(ew);
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param mobile 手机号
     * @return
     */
    @Override
    public User selectByMobile(String mobile) {
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("mobile", mobile);
        ew.or().eq("email", mobile);
        return super.selectOne(ew);
    }

    /**
     * 用户注册
     *
     * @param form 注册信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response register(RegisterForm form) {
        if (StringUtils.isBlank(form.getMobile()) && StringUtils.isBlank(form.getEmail())) {
            throw new GlobalDefaultException(-4);
        }
        if (StringUtils.isNotBlank(form.getMobile()) && StringUtils.isNotBlank(form.getEmail())) {
            throw new GlobalDefaultException(41002);
        }
        //邮箱校验
        if (StringUtils.isNotEmpty(form.getEmail())) {
            if (Optional.ofNullable(selectByMobile(form.getEmail())).isPresent()) {
                throw new GlobalDefaultException(40010);
            }
        }
        //手机号校验
        if (StringUtils.isNotEmpty(form.getMobile())) {
            if (Optional.ofNullable(selectByMobile(form.getMobile())).isPresent()) {
                throw new GlobalDefaultException(40002);
            }
        }
        User user = RegisterMapper.INSTANCE.map(form);
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(form.getCountryCode())
                .setTemplateCode(SmsTemplate.REGISTER_VERIFY.getCode())
                .setPhone(form.getMobile())
                .setEmail(form.getEmail())
                .setCode(form.getValidateCode());
        //手机/邮箱 验证码
        //boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
        if (false) {
            //验证码错误
            throw new GlobalDefaultException(20007);
        } else {
            String inviteId = "";
            String inviteRelation = "";
            String parent;
            if (StringUtils.isNotEmpty(form.getInvitionCode())) {
                EntityWrapper<User> e = new EntityWrapper<>();
                e.eq("invite_code", form.getInvitionCode());
                User inviter = super.selectOne(e);
                if (!Optional.ofNullable(inviter).isPresent()) {
                    //错误的邀请码
                    throw new GlobalDefaultException(20005);
                }
                inviteId = inviter.getId() + "";
                parent = inviter.getInviteRelation();
                if (StringUtils.isBlank(parent)) {
                    inviteRelation = inviteId + ",";
                } else {
                    String[] strings = parent.split(",");
                    inviteRelation = inviteId + "," + strings[0] + ",";
                    if (strings.length > 1) {
                        inviteRelation = inviteRelation + strings[1] + "";
                    }
                }
            }
            String password = form.getPassword();
            user.setDirectInviteid(inviteId);
            user.setInviteRelation(inviteRelation);
            user.setPassword(new BCryptPasswordEncoder().encode(password)); // 密码
            user.setLogins(0);                              // 登录次数
            user.setStatus(BaseStatus.EFFECTIVE.getCode()); // 状态
            user.setGaStatus(0);                            // 谷歌身份验证状态 默认0未启用
            user.setPaypassSetting(0);                      // 支付密码
            user.setType(UserType.CUSTOMER.getCode());      // 类型为：普通用户
            user.setLevel(-1);                              // 普通用户层级为-1
//            UserDetails userDetails;
            int count = baseMapper.insert(user);
            if (count > 0) {
                Long userId = user.getId();
                // 生成邀请码 U8 + 6位随机数
                //String inviteCode = ShareCodeUtil.idToCode(userId);
                // 暂时要求这么校验 后续再修改
                boolean flags = true;
                String inviteCode = "";
                while (flags) {
                    inviteCode = "u8" + getRandomCodeString(6);
                    EntityWrapper<User> e = new EntityWrapper<>();
                    e.eq("invite_code", inviteCode);
                    List<User> users = baseMapper.selectList(e);
                    if (users.isEmpty()) {
                        flags = false;
                    }
                }

                user.setInviteCode(inviteCode);
                baseMapper.updateById(user);
                //初始化资金账户 和 外汇账户
                boolean initAccount = accountServiceClient.syncAccount(user.getId());
                if (!initAccount) {
                    log.warn("初始化资金账户或外汇账户失败");
                    throw new GlobalDefaultException(2007);
                }
                //初始钱包库用户基本信息
                UserInfoDTO userInfo = new UserInfoDTO();
                userInfo.setId(userId)
                        .setCountryCode(user.getCountryCode())
                        .setUsername(form.getUserName())
                        .setMobile(user.getMobile());
                boolean initUserInfo = userInfoServiceClient.addUserInfo(userInfo);
                if (!initUserInfo) {
                    log.warn("初始钱包库用户基本信息失败");
                    throw new GlobalDefaultException(2007);
                }
                return Response.ok();
            }
            throw new GlobalDefaultException(2007);
        }
    }

    /**
     * 实名认证
     *
     * @param userDetails
     * @param form
     * @return
     */
    @Override
    @Transactional
    public Response updateAuthAccount(UserDetails userDetails, UserAuthInfoForm form) {
        //TODO 身份证姓名以及证件号第三方API识别
        /*try {
            if (!IdCardApi.verify(form.getRealName(), form.getIdCard())) {
                throw new GlobalDefaultException(2040);
            }
        } catch (IOException e) {
            throw new GlobalDefaultException(2040);
        }*/
        User sameUser = baseMapper.selectByIdCard(form.getIdCard());
        if (Optional.ofNullable(sameUser).isPresent()) {
            throw new GlobalDefaultException(2020);
        }
        User user2 = UserAuthInfoMapper.INSTANCE.map(form);
        user2.setId(userDetails.getId());
        int count = baseMapper.updateAuthName(user2);
        if (count < 1) {
            throw new GlobalDefaultException(20004);
        }
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(userDetails.getId())
                .setIdCard(form.getIdCard());
        userInfoServiceClient.updateUserInfo(userInfo);
        // 注册奖励
        rewardServiceClient.registerReward(userDetails.getId());
        User user = baseMapper.selectById(userDetails.getId());
        // 邀请奖励
        if (!StringUtils.isEmpty(user.getDirectInviteid())) {
            rewardServiceClient.inviteReward(Long.parseLong(user.getDirectInviteid()));
        }
        return Response.ok();
    }

    /**
     * 修改支付密码
     *
     * @param user
     * @param form
     * @return
     */
    @Override
    @Transactional
    public Response updatePayPassword(User user, ChangePasswordForm form) {
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(user.getCountryCode())
                .setTemplateCode(SmsTemplate.CHANGE_PAY_PWD_VERIFY.getCode())
                .setPhone(user.getMobile())
                .setEmail(user.getEmail())
                .setCode(form.getValidateCode());
        /*boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
        //验证码错误
        if (!flag) {
            throw new GlobalDefaultException(20007);
        }*/
        String oldPayPassword = user.getPaypassword();
        if (!new BCryptPasswordEncoder().matches(form.getOldpassword(), oldPayPassword)) {
            log.error("原交易密码错误");
            throw new GlobalDefaultException(2042);
        }
        int count = baseMapper.updatePayPassword(user.getId(), new BCryptPasswordEncoder().encode(form.getNewpassword()));
        if (count < 1) {
            throw new GlobalDefaultException(20004);
        }
        return Response.ok();
    }

    /**
     * 修改密码
     *
     * @param userDetails
     * @param form
     * @return
     */
    @Override
    public Response updatePassword(UserDetails userDetails, ChangePasswordForm form) {
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(userDetails.getCountryCode())
                .setTemplateCode(SmsTemplate.CHANGE_LOGIN_PWD_VERIFY.getCode())
                .setPhone(userDetails.getMobile())
                .setEmail(userDetails.getEmail())
                .setCode(form.getValidateCode());
        boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
//        if (!flag) {
        if (false) {
            //验证码错误
            throw new GlobalDefaultException(20007);
        }
        User user = baseMapper.selectById(userDetails.getId());
        String oldPassword = user.getPassword();
        if (!new BCryptPasswordEncoder().matches(form.getOldpassword(), oldPassword)) {
            log.error("原登录密码错误");
            throw new GlobalDefaultException(2041);
        }
        int count = baseMapper.updatePassword(user.getId(), new BCryptPasswordEncoder().encode(form.getNewpassword()));
        if (count < 1) {
            throw new GlobalDefaultException(20004);
        }
        //刷新token
        refreshToken();
        return Response.ok();
    }

    /**
     * 修改手机号
     *
     * @param userDetails
     * @param form
     * @return
     */
    @Override
    public Response updatePhone(UserDetails userDetails, ChangePhoneForm form) {
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(userDetails.getCountryCode())
                .setTemplateCode(SmsTemplate.CHANGE_PHONE_VERIFY.getCode())
                .setPhone(form.getNewMobilePhone())
                .setCode(form.getValidateCode());
        boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
        if (!flag) {
            //验证码错误
            throw new GlobalDefaultException(20007);
        }
        baseMapper.updatePhone(form.getNewMobilePhone(), form.getCountryCode(), userDetails.getId());
        //刷新token
        refreshToken();
        return Response.ok();
    }

    /**
     * 设置支付密码
     *
     * @param user
     * @param form
     * @return
     */
    @Override
    public Response setPayPassword(User user, ChangePayPasswordForm form) {
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(user.getCountryCode())
                .setTemplateCode(SmsTemplate.FORGOT_PAY_PWD_VERIFY.getCode())
                .setPhone(user.getMobile())
                .setEmail(user.getEmail())
                .setCode(form.getValidateCode());
        //TODO 验证码校验
        /*boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
        if (!flag) {
            //验证码错误
            throw new GlobalDefaultException(20007);
        }*/
        int count = baseMapper.updatePayPassword(user.getId(), new BCryptPasswordEncoder().encode(form.getPayPassword()));
        if (count < 1) {
            throw new GlobalDefaultException(20004);
        }
        return Response.ok();
    }

    /**
     * 设置密码
     *
     * @param form
     * @return
     */
    @Override
    public Response setPassword(SetPasswordForm form) {
        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(form.getCountryCode())
                .setTemplateCode(SmsTemplate.FORGOT_VERIFY.getCode())
                .setPhone(form.getMobile())
                .setEmail(form.getEmail())
                .setCode(form.getValidateCode());
        boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
//        if (!flag) {
        if (false) {
            //验证码错误
            throw new GlobalDefaultException(20007);
        }
        int updateCount = 2;
        for (int i = updateCount; i > 0; i--) {
            int count = baseMapper.updatePassWordByMobile(new BCryptPasswordEncoder().encode(form.getPassword()), form.getMobile());
            if (count == 1) {
                return Response.ok();
            }
        }
        throw new GlobalDefaultException(20004);
    }

    /**
     * 高级身份认证
     *
     * @param userDetails
     * @param forms
     * @return
     */
    @Override
    @Transactional
    public Response authUser(UserDetails userDetails, List<String> forms) {
        List<UserAuthInfo> list = new ArrayList<>();
        long authCode = System.currentTimeMillis();
        for (int i = 0; i < forms.size(); i++) {
            UserAuthInfo userAuthInfo = new UserAuthInfo();
            userAuthInfo.setImageUrl(forms.get(i));
            userAuthInfo.setSerialno(i + 1);
            userAuthInfo.setCreated(new Date());
            userAuthInfo.setUserId(userDetails.getId());
            userAuthInfo.setLastUpdateTime(new Date());
            userAuthInfo.setAuthCode(authCode);
            list.add(userAuthInfo);
        }
        UserAuthAuditRecord ur = new UserAuthAuditRecord();
        ur.setStatus(AuthStatus.AUTHING.getValue())
                .setCreated(new Date()).
                setUserId(userDetails.getId()).
                setStep(0).
                setAuthCode(authCode);
        userAuthAuditRecordService.insert(ur);
        boolean flag = userAuthInfoService.insertBatch(list);
        if (!flag) {
            throw new GlobalDefaultException(20004);
        }
        return Response.ok();
    }

    /**
     * 设置用户基本信息
     *
     * @param userDetails
     * @param form
     * @return
     */
    @Override
    public Response setUserBase(UserDetails userDetails, UserBaseForm form) {
        //判断用户名是否唯一
        EntityWrapper<User> e = new EntityWrapper<>();
        e.eq("username", form.getUsername());
        List<User> u = baseMapper.selectList(e);
        if (!u.isEmpty()) {
            log.error("用户名已存在");
            throw new GlobalDefaultException(40008);
        }
        //判断邮箱是否唯一
        if (StringUtils.isNotEmpty(form.getEmail())) {
            EntityWrapper<User> e1 = new EntityWrapper<>();
            e1.eq("email", form.getEmail());
            List<User> u1 = baseMapper.selectList(e1);
            if (!u1.isEmpty()) {
                log.error("邮箱已存在");
                throw new GlobalDefaultException(40010);
            }
        }

        int count = baseMapper.updateUserBase(userDetails.getId(),
                form.getUsername(),
                form.getEmail(),
                new BCryptPasswordEncoder().encode(form.getPayPassword()));
        if (count < 1) {
            throw new GlobalDefaultException(20004);
        }
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(userDetails.getId())
                .setUsername(form.getUsername())
                .setEmail(form.getEmail());
        userInfoServiceClient.updateUserInfo(userInfo);
        return Response.ok();
    }

    /**
     * 查询邀请列表
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<User> selectListByInviteId(long userId) {
        return baseMapper.selectListByInviteId(userId);
    }

    /**
     * 代理商注册
     *
     * @param agentRegister 代理商注册信息
     * @return
     */
    @Override
    @Transactional
    public Response agentRegister(AgentRegisterDTO agentRegister) {
        if (Optional.ofNullable(this.selectByMobile(agentRegister.getMobile())).isPresent()) {
            // 用户已注册
            throw new GlobalDefaultException(40002);
        }

        RandCodeVerifyDTO randCodeVerifyDTO = new RandCodeVerifyDTO()
                .setCountryCode(agentRegister.getCountryCode())
                .setTemplateCode(SmsTemplate.REGISTER_VERIFY.getCode())
                .setPhone(agentRegister.getMobile())
                .setEmail(agentRegister.getEmail())
                .setCode(agentRegister.getValidateCode());
        /*boolean flag = randCodeServiceClient.verify(randCodeVerifyDTO);
        if (!flag) {
            // 验证码错误
            throw new GlobalDefaultException(20007);
        }*/
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("invite_code", agentRegister.getInvitionCode());
        User agentUser = super.selectOne(wrapper);
        if (agentUser == null || UserType.AGENT.getCode() != agentUser.getType()) {
            // 邀请码错误
            throw new GlobalDefaultException(20005);
        }
        User user = new User();
        String inviteRelation = agentUser.getInviteRelation();
        user.setInviteRelation(StringUtils.isEmpty(inviteRelation) ? "" : inviteRelation + agentUser.getId() + ",")
                .setDirectInviteid(String.valueOf(agentUser.getId()))
                .setCountryCode(agentRegister.getCountryCode())
                .setMobile(agentRegister.getMobile())
                .setRealName(agentRegister.getRealName())
                .setPassword(new BCryptPasswordEncoder().encode(agentRegister.getPassword()))
                .setLogins(0)
                .setStatus(0)
                .setPaypassSetting(0)
                .setType(UserType.AGENT.getCode())
                .setLevel(agentUser.getLevel() + 1)
                .setEmail(agentRegister.getEmail());
        int count = baseMapper.insert(user);
        UserDetails userDetails;
        if (count > 0) {
            Long userId = user.getId();
            // 生成邀请码
            //String inviteCode = ShareCodeUtil.idToCode(userId);
            // 生成邀请码 U8 + 6位随机数
            //String inviteCode = ShareCodeUtil.idToCode(userId);
            // 暂时要求这么校验 后续再修改
            boolean flags = true;
            String inviteCode = "";
            while (flags) {
                inviteCode = "u8" + getRandomCodeString(6);
                EntityWrapper<User> e = new EntityWrapper<>();
                e.eq("invite_code", inviteCode);
                List<User> users = baseMapper.selectList(e);
                if (users.isEmpty()) {
                    flags = false;
                }
            }
            user.setInviteCode(inviteCode);
            baseMapper.updateById(user);
            // 验证成功
            UserLoginForm userLoginForm = new UserLoginForm();
            userLoginForm.setUsername(agentRegister.getMobile())
                    .setPassword(agentRegister.getPassword())
                    .setType(UserType.AGENT.getCode());
            userDetails = userDetailsService.login(userLoginForm);
            // 初始化资金账户 和 外汇账户
            boolean initAccount = accountServiceClient.syncAccount(user.getId());
            if (!initAccount) {
                log.warn("代理商注册初始化资金账户或外汇账户失败");
                throw new GlobalDefaultException(2007);
            }
            // 初始钱包库用户基本信息
            UserInfoDTO userBase = new UserInfoDTO();
            userBase.setId(userId)
                    .setCountryCode(agentRegister.getCountryCode())
                    .setMobile(agentRegister.getMobile())
                    .setRealName(agentRegister.getRealName());
            boolean initUserInfo = userInfoServiceClient.addUserInfo(userBase);
            if (!initUserInfo) {
                log.warn("代理商初始钱包库用户基本信息失败");
                throw new GlobalDefaultException(2007);
            }
            return Response.ok(userDetails);
        }
        throw new GlobalDefaultException(2007);
    }

    /**
     * 查询代理商邀请的用户列表
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<User> selectAgentInvitation(Long userId) {
        return baseMapper.selectAgentInvitation(userId);
    }

    /**
     * 查询管理员用户
     *
     * @param userName
     * @return
     */
    @Override
    public User queryAdminUser(String userName) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("username", userName)
                .eq("status", BaseStatus.EFFECTIVE.getCode())
                .eq("type", 0);
        return super.selectOne(wrapper);
    }

    @Override
    public Object registerForPhp(String token) {
        //PHP那边注册的同时，PHP调用该接口 作用是将用户信息写入数据库
        //{"phoneCode":86,"iat":1611387354,"username":"15989001760"}
        Map<String, Object> map = TokenUtil.parserImToken(token);
        String phoneCode = String.valueOf(map.get("phoneCode"));
        String username = String.valueOf(map.get("username"));
        //String password = (String) map.get("password");
        if (StringUtils.isBlank(phoneCode) || StringUtils.isBlank(username)) {
            throw new GlobalDefaultException(-4);
        }

        User user = this.selectByPhone(username);
        if (user != null) {
            throw new GlobalDefaultException(40002);
        }
        user = new User();
        user.setCountryCode(phoneCode);
        user.setMobile(username);
        //TODO JAVA这边不保存用户密码 避免token传输造成泄露
        user.setPassword(new BCryptPasswordEncoder().encode("")); // 密码
        user.setLogins(0);                              // 登录次数
        user.setStatus(BaseStatus.EFFECTIVE.getCode()); // 状态
        user.setGaStatus(0);                            // 谷歌身份验证状态 默认0未启用
        user.setPaypassSetting(0);                      // 支付密码
        user.setType(UserType.CUSTOMER.getCode());      // 类型为：普通用户
        user.setLevel(-1);                              // 普通用户层级为-1
        user.setCreated(new Date());
        int count = baseMapper.insert(user);
        if (count > 0) {
            Long userId = user.getId();
            baseMapper.updateById(user);
            //初始化资金账户 和 外汇账户
            boolean initAccount = accountServiceClient.syncAccount(user.getId());
            if (!initAccount) {
                log.warn("初始化资金账户或外汇账户失败");
                throw new GlobalDefaultException(2007);
            }
            //初始钱包库用户基本信息
            UserInfoDTO userInfo = new UserInfoDTO();
            userInfo.setId(userId)
                    .setCountryCode(user.getCountryCode())
                    .setUsername(username)
                    .setMobile(user.getMobile());
            boolean initUserInfo = userInfoServiceClient.addUserInfo(userInfo);
            if (!initUserInfo) {
                log.warn("初始钱包库用户基本信息失败");
                throw new GlobalDefaultException(2007);
            }
            return Response.ok();
        }
        return Response.err(ResultCode.ERROR);
    }

    @Override
    public User selectByPhone(String phone) {
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("mobile", phone);
        return super.selectOne(ew);
    }

    /**
     * 刷新 token
     *
     * @return
     * @throws AuthenticationException
     */
    private Object refreshToken() throws AuthenticationException {
        String accessToken = tokenProvider.resolveToken(request);
        if (!Strings.isNullOrEmpty(accessToken)) {
            String jwt = userDetailsService.refreshToken(accessToken);
            return Response.ok(jwt);
        } else {
            //无效凭证，access_token无效或不是最新的。
            throw new GlobalDefaultException(40001);
        }
    }

    /**
     * 生成随机字符串
     *
     * @return
     */
    public String getRandomCodeString(int length) {
        StringBuffer code = new StringBuffer();
        if (length == 0) {
            return code.toString();
        }
        String sources = "0123456789abcdefghijklmnopqrstuvwxyz";
        Random rand = new Random();
        for (int i = 0; i < length; i++) {
            code.append(sources.charAt(rand.nextInt(sources.length() - 1)));
        }
        return code.toString();
    }

}
